import { ToolKit } from '../../lib/utils/toolkit'
import {
  getAllRequires,
  RESOURCE_NAME,
  RESOURCE_TAG,
  RESOURCES_CONFIG,
  SYMBOLS,
} from '../interfaces'
import { IS_PRODUCTION } from './app'
import { logger } from './logger_config'

/**
 * 校验资源完整性
 */
export async function checkAllResourceIntegrity(): Promise<void> {
  if (IS_PRODUCTION)
    return

  // 1. 校验 require 资源
  getAllRequires().forEach((url) => {
    const integrity = ToolKit.browser.url.extractIntegrityFromUrl(url)?.value

    if (integrity) {
      logger.info(`[IntegrityCheck] [require] ${SYMBOLS.STATUS.SUCCESS} 该资源已包含资源完整性哈希值：${integrity}`, url)
    }
    else {
      logger.warn(`[IntegrityCheck] [require] 该资源未包含资源完整性哈希值`, url)
    }
  })

  // 2. 校验 resource 资源
  for (const config of RESOURCES_CONFIG.filter(config => config.tag === RESOURCE_TAG.RESOURCE && config.check)) {
    const { id, url } = config
    await ToolKit.resource.checkResourceIntegrity(id, url)
  }

  logger.important('[IntegrityCheck] 所有资源完整性校验完成')
}

/**
 * 获取 Nerd Fonts CSS 内容
 */
export function getNerdFontsCSSContent(): string {
  const originalCSS = ToolKit.resource.getResourceText(RESOURCE_NAME.NERD_FONTS_CSS)
  return fixNerdFontsFontPath(originalCSS)
}

/**
 * 修复 Nerd Fonts CSS 中的字体路径
 */
function fixNerdFontsFontPath(css: string): string {
  // 获取字体文件的 Data URL 或正确路径
  const fontUrl = ToolKit.resource.getResourceURL(RESOURCE_NAME.NERD_FONTS_WOFF2)

  // 替换相对路径为正确的 URL
  return css.replace(
    /url\("\.\.\/fonts\/([^"]+)"\)/g,
    `url("${fontUrl}")`,
  )
}
